/**
 * SEO友好的评论系统
 * 默认渲染前几条评论，AJAX加载更多
 */
class CommentsManager {
    constructor(options) {
        this.goodsId = options.goodsId;
        this.userInfo = options.userInfo || null;
        this.currentPage = 1;
        this.pageSize = 5;
        this.currentSort = 'create_time';
        this.loading = false;
        this.submitting = false;
        this.replyingTo = null;
        this.replyToId = 0; // 回复的评论ID
        this.initialized = false; // 是否已初始化加载评论

        // 上传相关
        this.uploadedImages = [];
        this.uploadedFiles = [];
        this.isUploading = false;

        this.init();
    }

    init() {
        this.bindEvents();
        this.initSortDropdown();
        // 不在初始化时加载评论，等待tab激活时再加载
    }

    // 当评论tab被激活时调用
    loadCommentsOnTabActive() {
        if (!this.initialized) {
            this.initialized = true;
            this.loadComments(true); // 首次加载
        }
    }

    bindEvents() {
        // 评论输入框事件 - 使用jQuery
        $('#comment-textarea').on('input', (e) => this.handleInput(e));

        // 提交按钮
        $('#submit-btn').on('click', () => this.handleSubmit());

        // 重置按钮
        $('#reset-btn').on('click', () => this.handleReset());

        // 图片上传
        $('#image-upload').on('change', (e) => this.handleImageUpload(e));

        // 附件上传
        $('#file-upload').on('change', (e) => this.handleFileUpload(e));

        // 上传按钮点击 - 使用更精确的选择器
        $(document).on('click', 'button[title="上传图片"]', (e) => {
            e.preventDefault();
            if (this.userInfo && this.userInfo.id) {
                $('#image-upload').click();
            } else {
                if (typeof showError === 'function') {
                    showError('请先登录');
                } else {
                    alert('请先登录');
                }
            }
        });

        $(document).on('click', 'button[title="上传附件"]', (e) => {
            e.preventDefault();
            if (this.userInfo && this.userInfo.id) {
                $('#file-upload').click();
            } else {
                if (typeof showError === 'function') {
                    showError('请先登录');
                } else {
                    alert('请先登录');
                }
            }
        });

        // 加载更多
        $('#load-more-btn').on('click', () => this.loadMoreComments());

        // 排序选项
        $('.sort-option').on('click', (e) => {
            const value = $(e.currentTarget).data('value');
            this.handleSortChange(value);
        });

        // 排序下拉菜单
        $('.sort-dropdown').on('click', () => this.toggleSortDropdown());

        // 全局点击事件（关闭下拉菜单）
        $(document).on('click', (e) => this.handleClickOutside(e));

        // 回复取消按钮
        $(document).on('click', '#cancel-reply-btn', () => this.cancelReply());
    }

    // 处理输入事件
    handleInput(e) {
        const content = $(e.target).val();

        // 更新字符计数
        $('#content-length').text(content.length);

        // 更新按钮状态
        this.updateSubmitButton(content);

        // 显示/隐藏重置按钮
        if (content.trim()) {
            $('#reset-btn').removeClass('hidden');
        } else {
            $('#reset-btn').addClass('hidden');
        }
    }

    // 更新提交按钮状态
    updateSubmitButton(content = null) {
        const $submitBtn = $('#submit-btn');
        const currentContent = content !== null ? content : $('#comment-textarea').val();
        const minLength = this.replyToId > 0 ? 2 : 3; // 回复最少2个字符，评论最少3个字符

        // 检查用户是否登录
        const isLoggedIn = this.userInfo && this.userInfo.id;

        const canSubmit = isLoggedIn &&
            currentContent &&
            currentContent.trim().length >= minLength &&
            !this.submitting;

        $submitBtn.prop('disabled', !canSubmit);
        $submitBtn.text(this.submitting ? '提交中...' : (this.replyToId > 0 ? '提交回复' : '发表评论'));

        // 更新按钮样式
        if (canSubmit) {
            $submitBtn.removeClass('opacity-50 cursor-not-allowed').addClass('hover:opacity-90');
        } else {
            $submitBtn.addClass('opacity-50 cursor-not-allowed').removeClass('hover:opacity-90');
        }
    }

    // 提交评论
    async handleSubmit() {
        if (!this.userInfo) {
            showError('请先登录');
            return;
        }

        const content = $('#comment-textarea').val().trim();
        const minLength = this.replyToId > 0 ? 2 : 3; // 回复最少2个字符，评论最少3个字符

        if (!content || content.length < minLength) {
            showError(`${this.replyToId > 0 ? '回复' : '评论'}内容至少需要${minLength}个字符`);
            return;
        }

        this.submitting = true;
        this.updateSubmitButton();

        try {
            const submitData = {
                goods_id: this.goodsId,
                content: content,
                parent_id: this.replyToId,
                images: this.uploadedImages.map(img => img.url || img),
                attachments: this.uploadedFiles.map(file => file.url || file)
            };

            const response = await $.ajax({
                url: '/web/comment/submit',
                type: 'POST',
                data: submitData,
                dataType: 'json'
            });

            if (response.code === 1) {
                showSuccess(response.msg || '评论提交成功');
                this.handleReset();
                // 动态刷新评论列表，不刷新页面
                this.refreshComments();
            } else {
                showError(response.msg || '评论提交失败');
            }
        } catch (error) {
            showError('网络连接失败');
            console.error(error);
        } finally {
            this.submitting = false;
            this.updateSubmitButton();
        }
    }

    // 重置表单
    handleReset() {
        $('#comment-textarea').val('');
        $('#content-length').text('0');
        $('#reset-btn').addClass('hidden');

        // 如果是回复状态，取消回复
        if (this.replyToId > 0) {
            this.cancelReply();
        }

        this.uploadedImages = [];
        this.uploadedFiles = [];
        this.hideUploadedImages();
        this.hideUploadedFiles();
        this.updateSubmitButton();
    }

    // 设置回复状态
    setReply(commentId, userName) {
        this.replyToId = commentId;

        // 更新文本框提示
        $('#comment-textarea').attr('placeholder', `回复 ${userName}...`).focus();

        // 添加取消回复按钮
        if ($('#reply-info').length === 0) {
            const replyInfo = $('<div id="reply-info" class="px-4 py-2 bg-gray-100 rounded-t-lg flex items-center justify-between"></div>');
            replyInfo.html(`
                <span class="text-sm text-gray-800">回复: <strong class="text-blue-600">${userName}</strong></span>
                <button id="cancel-reply-btn" class="text-sm text-gray-500 hover:text-blue-600">取消回复</button>
            `);
            $('#comment-textarea').before(replyInfo);
        } else {
            $('#reply-info strong').text(userName);
        }

        // 更新提交按钮文本
        this.updateSubmitButton();

        // 滚动到评论框
        $('html, body').animate({
            scrollTop: $('#comment-textarea').offset().top - 100
        }, 500);
    }

    // 取消回复
    cancelReply() {
        this.replyToId = 0;
        $('#reply-info').remove();
        $('#comment-textarea').attr('placeholder', this.userInfo ? '写下你的评论...' : '');
        this.updateSubmitButton();
    }

    // 刷新评论列表（提交评论后调用）
    async refreshComments() {
        // 重置页码并清空评论列表
        this.currentPage = 1;
        $('#comments-list').empty();

        // 加载第一页评论
        await this.loadMoreComments();
    }

    // 加载更多评论
    async loadMoreComments() {
        if (this.loading) return;

        this.loading = true;
        this.showLoading();

        try {
            const response = await $.ajax({
                url: '/web/comment/lists',
                type: 'POST',  // 保持POST请求，与路由配置一致
                data: {
                    goods_id: this.goodsId,
                    page: this.currentPage,
                    limit: this.pageSize,
                    sort: this.currentSort
                },
                dataType: 'json'
            });

            if (response.code === 1) {
                const data = response.data;

                // 更新评论总数
                $('#comments-total').text(data.total || 0);

                if (data.list && data.list.length > 0) {
                    this.appendComments(data.list);
                    this.hideEmptyState();
                } else if (this.currentPage === 1) {
                    // 如果是第一页且没有数据，显示空状态
                    this.showEmptyState();
                }

                // 请求成功后再递增页码
                this.currentPage++;

                // 更新加载更多按钮状态
                if (!data.has_more) {
                    this.hideLoadMoreButton();
                } else {
                    this.showLoadMoreButton();
                }
            } else {
                showError(response.msg || '加载评论失败');
                this.currentPage--; // 回退页码
            }
        } catch (error) {
            showError('网络连接失败');
            console.error(error);
            this.currentPage--; // 回退页码
        } finally {
            this.loading = false;
            this.hideLoading();
        }
    }

    // 加载评论（首次加载或重新加载）
    async loadComments(isFirstLoad = false) {
        // 重置页码
        this.currentPage = 1;

        if (isFirstLoad) {
            // 首次加载：隐藏初始加载状态，清空评论列表
            $('#initial-loading').hide();
            $('#comments-list').empty();
        } else {
            // 重新加载：清空评论列表
            $('#comments-list').empty();
        }

        // 加载评论
        await this.loadMoreComments();
    }

    // 追加评论到列表
    appendComments(comments) {
        const $commentsList = $('#comments-list');
        if (!$commentsList.length) return;

        // 获取当前已加载的评论数量作为起始索引
        const currentIndex = this.getCommentIndex();

        comments.forEach((comment, index) => {
            // 计算正确的索引 = 当前已有评论数 + 新评论的索引
            const commentHtml = this.renderCommentItem(comment, currentIndex + index);
            $commentsList.append(commentHtml);
        });

        // 处理图片预览
        this.initImagePreviews();
    }

    // 获取当前评论索引
    getCommentIndex() {
        // 返回当前页面上评论元素的数量
        return $('#comments-list').children('.comment-item').length;
    }

    // 渲染评论项（主要用于AJAX加载）
    renderCommentItem(comment, index) {
        const floorNumber = this.getFloorDisplay(index);
        const userId = this.userInfo ? this.userInfo.id : 0;
        const isOwner = userId && userId == comment.user_id;

        // 处理图片和附件
        let imagesHtml = '';
        let attachmentsHtml = '';

        // 处理图片
        if (comment.images && comment.images.length > 0) {
            imagesHtml = `
                <div class="mt-3 flex flex-wrap gap-2">
                    ${comment.images.map((img, i) => `
                        <div class="relative group cursor-pointer image-preview-item" 
                             data-images='${JSON.stringify(comment.images)}'
                             data-index="${i}"
                             onclick="openImagePreviewFromData(this)">
                            <img src="${img}" alt="评论图片" class="w-20 h-20 object-cover rounded">
                        </div>
                    `).join('')}
                </div>
            `;
        }

        // 处理附件
        if (comment.attachments && comment.attachments.length > 0) {
            attachmentsHtml = `
                <div class="mt-3 space-y-2">
                    ${comment.attachments.map(file => `
                        <div class="flex items-center gap-3 p-2 bg-gray-100 rounded-lg">
                            <i class="fas fa-file w-5 h-5 text-gray-500"></i>
                            <div class="flex-1 min-w-0">
                                <div class="text-sm font-medium text-blue-600 truncate">${file.name}</div>
                            </div>
                            <button class="px-2 py-1 text-xs text-blue-600 hover:text-blue-800 transition-colors duration-200" onclick="downloadFile('${file.url}', '${file.name}')">
                                <i class="fas fa-download"></i> 下载
                            </button>
                        </div>
                    `).join('')}
                </div>
            `;
        }

        // 渲染回复
        let repliesHtml = '';
        if (comment.replies && comment.replies.length > 0) {
            repliesHtml = `
                <div class="mt-4 pl-4 border-l-2 border-gray-200 space-y-3">
                    ${comment.replies.map(reply => {
                // 处理回复中的图片
                let replyImagesHtml = '';
                if (reply.images && reply.images.length > 0) {
                    replyImagesHtml = `
                                <div class="mb-3">
                                    <div class="flex flex-wrap gap-2 items-center">
                                        ${reply.images.map((img, i) => `
                                            <div class="cursor-pointer image-preview-item" 
                                                 data-images='${JSON.stringify(reply.images)}'
                                                 data-index="${i}"
                                                 onclick="openImagePreviewFromData(this)">
                                                <img src="${img}" alt="回复图片" class="w-24 h-24 object-cover rounded hover:opacity-80 transition-opacity duration-200">
                                            </div>
                                        `).join('')}
                                    </div>
                                </div>
                            `;
                }

                // 处理回复中的附件
                let replyAttachmentsHtml = '';
                if (reply.attachments && reply.attachments.length > 0) {
                    replyAttachmentsHtml = `
                                <div class="mb-3">
                                    <div class="space-y-2">
                                        ${reply.attachments.map(file => `
                                            <div class="flex items-center gap-3 p-2 bg-gray-50 rounded cursor-pointer hover:bg-gray-100 transition-colors duration-200 text-sm"
                                                onclick="downloadFile('${file.url}', '${file.name}')">
                                                <i class="fas fa-file w-4 h-4 text-gray-500"></i>
                                                <span class="flex-1 truncate text-blue-600">${file.name}</span>
                                                <i class="fas fa-download w-3 h-3 text-gray-400"></i>
                                            </div>
                                        `).join('')}
                                    </div>
                                </div>
                            `;
                }

                return `
                        <div class="group py-2 border-b border-gray-200" data-reply-id="${reply.id}">
                            <div class="flex gap-3">
                                <div class="flex-shrink-0">
                                    <img src="${reply.user?.avatar}" alt="${reply.user?.nickname || '用户'}" class="w-8 h-8 rounded-full object-cover">
                                </div>
                                <div class="flex-1 min-w-0">
                                    <div class="flex items-center gap-2 mb-2">
                                        <span class="font-medium text-blue-600 text-sm">${reply.user?.nickname || '用户'}</span>
                                        ${reply.is_admin ? '<span class="px-1.5 py-0.5 text-xs bg-orange-100 text-orange-600 rounded-full">管理员</span>' : ''}
                                        <div class="ml-auto text-xs text-gray-500"></div>
                                    </div>
                                    <div class="text-gray-800 leading-relaxed mb-3 text-sm">${reply.content}</div>
                                    
                                    <!-- 回复中的图片 -->
                                    ${replyImagesHtml}
                                    
                                    <!-- 回复中的附件 -->
                                    ${replyAttachmentsHtml}
                                    
                                    <div class="flex items-center justify-between mt-2">
                                        <span class="text-gray-500 text-sm">${this.formatTime(reply.create_time)}</span>
                                        <div class="flex items-center gap-3 text-sm ">
                                            <button class="flex items-center gap-1 text-gray-500 hover:text-blue-600 transition-colors duration-200" onclick="handleCommentLike(${reply.id})">
                                                <i class="fas fa-thumbs-up w-4 h-4 ${reply.is_liked ? 'text-blue-600' : ''}"></i>
                                                <span class="text-xs ${reply.is_liked ? 'text-blue-600' : ''}">${reply.likes > 0 ? reply.likes : '赞'}</span>
                                            </button>
                                            <button class="flex items-center gap-1 text-gray-500 hover:text-blue-600 transition-colors duration-200" onclick="window.commentsManager.setReply(${reply.id}, '${reply.user?.nickname || '用户'}')">
                                                <i class="fas fa-reply w-4 h-4"></i>
                                                <span class="text-xs">回复</span>
                                            </button>
                                            ${userId == reply.user_id ? `
                                            <button class="flex items-center gap-1 text-gray-500 hover:text-red-500 transition-colors duration-200" onclick="handleCommentDelete(${reply.id})">
                                                <i class="fas fa-trash-alt w-4 h-4"></i>
                                                <span class="text-xs">删除</span>
                                            </button>
                                            ` : ''}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        `;
            }).join('')}
                    ${comment.replies.length >= 3 && comment.total_replies > comment.replies.length ? `
                        <button class="text-sm text-blue-600 hover:underline" onclick="loadMoreReplies(${comment.id})">
                            查看更多回复 (${comment.total_replies - comment.replies.length})
                        </button>
                    ` : ''}
                </div>
            `;
        }

        return `
            <div class="comment-item border-b border-gray-200 pb-4 mb-4" data-comment-id="${comment.id}">
                <div class="group py-4">
                    <div class="flex gap-3">
                        <div class="flex-shrink-0">
                            <img src="${comment.user?.avatar}" alt="${comment.user?.nickname || '用户'}" class="w-10 h-10 rounded-full object-cover">
                        </div>
                        <div class="flex-1 min-w-0">
                            <div class="flex items-center gap-2 mb-2">
                                <span class="font-medium text-blue-600 text-md">${comment.user?.nickname || '用户'}</span>
                                ${comment.is_admin ? '<span class="px-2 py-0.5 text-xs bg-orange-100 text-orange-600 rounded-full">管理员</span>' : ''}
                                <div class="ml-auto text-xs text-gray-500">${floorNumber}</div>
                            </div>
                            <div class="text-gray-800 leading-relaxed mb-2">${comment.content}</div>
                            
                            ${imagesHtml}
                            ${attachmentsHtml}
                            
                            <div class="flex items-center justify-between mt-3">
                                <span class="text-gray-500 text-sm">${this.formatTime(comment.create_time)}</span>
                                <div class="flex items-center gap-3 text-sm ">
                                    <button class="flex items-center gap-1 text-gray-500 hover:text-blue-600 transition-colors duration-200" onclick="handleCommentLike(${comment.id})">
                                        <i class="fas fa-thumbs-up w-4 h-4 ${comment.is_liked ? 'text-blue-600' : ''}"></i>
                                        <span class="text-xs ${comment.is_liked ? 'text-blue-600' : ''}">${comment.likes > 0 ? comment.likes : '赞'}</span>
                                    </button>
                                    <button class="flex items-center gap-1 text-gray-500 hover:text-blue-600 transition-colors duration-200" onclick="window.commentsManager.setReply(${comment.id}, '${comment.user?.nickname || '用户'}')">
                                        <i class="fas fa-reply w-4 h-4"></i>
                                        <span class="text-xs">回复</span>
                                    </button>
                                    ${isOwner ? `
                                    <button class="flex items-center gap-1 text-gray-500 hover:text-red-500 transition-colors duration-200" onclick="handleCommentDelete(${comment.id})">
                                        <i class="fas fa-trash-alt w-4 h-4"></i>
                                        <span class="text-xs">删除</span>
                                    </button>
                                    ` : ''}
                                </div>
                            </div>
                            
                            ${repliesHtml}
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    // 初始化图片预览
    initImagePreviews() {
        // 这里可以集成图片预览库，如lightbox等
    }

    // 渲染单个回复项
    renderReplyItem(reply) {
        const userId = this.userInfo ? this.userInfo.id : 0;

        // 处理回复中的图片
        let replyImagesHtml = '';
        if (reply.images && reply.images.length > 0) {
            replyImagesHtml = `
                <div class="mb-3">
                    <div class="flex flex-wrap gap-2 items-center">
                        ${reply.images.map((img, i) => `
                            <div class="cursor-pointer image-preview-item" 
                                 data-images='${JSON.stringify(reply.images)}'
                                 data-index="${i}"
                                 onclick="openImagePreviewFromData(this)">
                                <img src="${img}" alt="回复图片" class="w-24 h-24 object-cover rounded hover:opacity-80 transition-opacity duration-200">
                            </div>
                        `).join('')}
                    </div>
                </div>
            `;
        }

        // 处理回复中的附件
        let replyAttachmentsHtml = '';
        if (reply.attachments && reply.attachments.length > 0) {
            replyAttachmentsHtml = `
                <div class="mb-3">
                    <div class="space-y-2">
                        ${reply.attachments.map(file => `
                            <div class="flex items-center gap-3 p-2 bg-gray-50 rounded cursor-pointer hover:bg-gray-100 transition-colors duration-200 text-sm"
                                onclick="downloadFile('${file.url}', '${file.name}')">
                                <i class="fas fa-file w-4 h-4 text-gray-500"></i>
                                <span class="flex-1 truncate text-blue-600">${file.name}</span>
                                <i class="fas fa-download w-3 h-3 text-gray-400"></i>
                            </div>
                        `).join('')}
                    </div>
                </div>
            `;
        }

        return `
            <div class="group py-2 border-b border-gray-200" data-reply-id="${reply.id}">
                <div class="flex gap-3">
                    <div class="flex-shrink-0">
                        <img src="${reply.user?.avatar}" alt="${reply.user?.nickname || '用户'}" class="w-8 h-8 rounded-full object-cover">
                    </div>
                    <div class="flex-1 min-w-0">
                        <div class="flex items-center gap-2 mb-2">
                            <span class="font-medium text-blue-600 text-sm">${reply.user?.nickname || '用户'}</span>
                            ${reply.is_admin ? '<span class="px-1.5 py-0.5 text-xs bg-orange-100 text-orange-600 rounded-full">管理员</span>' : ''}
                            <div class="ml-auto text-xs text-gray-500">${this.formatTime(reply.create_time)}</div>
                        </div>
                        <div class="text-gray-800 leading-relaxed mb-3 text-sm">${reply.content}</div>
                        
                        <!-- 回复中的图片 -->
                        ${replyImagesHtml}
                        
                        <!-- 回复中的附件 -->
                        ${replyAttachmentsHtml}
                        
                        <div class="flex items-center justify-between mt-2">
                            <div class="flex items-center gap-3 text-sm ">
                                <button class="flex items-center gap-1 text-gray-500 hover:text-blue-600 transition-colors duration-200" onclick="handleCommentLike(${reply.id})">
                                    <i class="fas fa-thumbs-up w-3 h-3 ${reply.is_liked ? 'text-blue-600' : ''}"></i>
                                    <span class="text-xs ${reply.is_liked ? 'text-blue-600' : ''}">${reply.likes > 0 ? reply.likes : '赞'}</span>
                                </button>
                                <button class="flex items-center gap-1 text-gray-500 hover:text-blue-600 transition-colors duration-200" onclick="window.commentsManager.setReply(${reply.id}, '${reply.user?.nickname || '用户'}')">
                                    <i class="fas fa-reply w-3 h-3"></i>
                                    <span class="text-xs">回复</span>
                                </button>
                                ${userId == reply.user_id ? `
                                <button class="flex items-center gap-1 text-gray-500 hover:text-red-500 transition-colors duration-200" onclick="handleCommentDelete(${reply.id})">
                                    <i class="fas fa-trash-alt w-3 h-3"></i>
                                    <span class="text-xs">删除</span>
                                </button>
                                ` : ''}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    // 获取楼层显示
    getFloorDisplay(index) {
        const floorNumber = index + 1;
        if (floorNumber === 1) return '沙发';
        if (floorNumber === 2) return '板凳';
        return `${floorNumber}#`;
    }

    // 时间格式化
    formatTime(timeStr) {
        const now = new Date();
        const time = new Date(timeStr);
        const diff = now.getTime() - time.getTime();

        const minutes = Math.floor(diff / (1000 * 60));
        const hours = Math.floor(diff / (1000 * 60 * 60));
        const days = Math.floor(diff / (1000 * 60 * 60 * 24));

        if (days === 0) {
            if (minutes < 60) {
                return minutes <= 0 ? '刚刚' : `${minutes}分钟前`;
            }
            return `${hours}小时前`;
        }

        if (days === 1) {
            return `昨天 ${time.getHours().toString().padStart(2, '0')}:${time.getMinutes().toString().padStart(2, '0')}`;
        }

        if (time.getFullYear() === now.getFullYear()) {
            return `${(time.getMonth() + 1).toString().padStart(2, '0')}-${time.getDate().toString().padStart(2, '0')}`;
        }

        return `${time.getFullYear()}-${(time.getMonth() + 1).toString().padStart(2, '0')}-${time.getDate().toString().padStart(2, '0')}`;
    }

    // 显示加载状态
    showLoading() {
        $('#loading-state').removeClass('hidden');
    }

    // 隐藏加载状态
    hideLoading() {
        $('#loading-state').addClass('hidden');
    }

    // 显示加载更多按钮
    showLoadMoreButton() {
        $('#load-more-container').removeClass('hidden');
    }

    // 隐藏加载更多按钮
    hideLoadMoreButton() {
        $('#load-more-container').addClass('hidden');
    }

    // 显示空状态
    showEmptyState() {
        // 如果不存在空状态元素，则创建一个
        if ($('#empty-state').length === 0) {
            const emptyState = $(`
                <div id="empty-state" class="text-center py-12">
                    <div class="flex flex-col items-center justify-center">
                        <i class="fas fa-comments w-16 h-16 text-gray-500 mb-4"></i>
                        <p class="text-gray-500 text-lg mb-1">暂无评论</p>
                        <p class="text-gray-500 text-sm">快来发表第一条评论吧！</p>
                    </div>
                </div>
            `);
            $('#comments-list').append(emptyState);
        } else {
            $('#empty-state').removeClass('hidden');
        }
    }

    // 隐藏空状态
    hideEmptyState() {
        $('#empty-state').addClass('hidden');
    }

    // 隐藏已上传的图片
    hideUploadedImages() {
        $('#uploaded-images-container').addClass('hidden');
    }

    // 显示已上传的图片
    showUploadedImages() {
        $('#uploaded-images-container').removeClass('hidden');
    }

    // 隐藏已上传的文件
    hideUploadedFiles() {
        $('#uploaded-files-container').addClass('hidden');
    }

    // 显示已上传的文件
    showUploadedFiles() {
        $('#uploaded-files-container').removeClass('hidden');
    }

    // 显示上传进度
    showUploadProgress() {
        $('#upload-progress-container').removeClass('hidden');
    }

    // 隐藏上传进度
    hideUploadProgress() {
        $('#upload-progress-container').addClass('hidden');
    }

    // 排序相关方法（简化版）
    initSortDropdown() {
        // 初始化排序下拉菜单状态
    }

    toggleSortDropdown() {
        const menu = document.getElementById('sort-dropdown-menu');
        const arrow = document.getElementById('sort-arrow');

        if (menu && arrow) {
            if (menu.classList.contains('hidden')) {
                menu.classList.remove('hidden');
                arrow.classList.add('rotate-180');
            } else {
                menu.classList.add('hidden');
                arrow.classList.remove('rotate-180');
            }
        }
    }

    handleSortChange(sortValue) {
        this.currentSort = sortValue;

        // 更新UI
        const menu = document.getElementById('sort-dropdown-menu');
        const arrow = document.getElementById('sort-arrow');
        const label = document.getElementById('current-sort-label');

        if (menu) menu.classList.add('hidden');
        if (arrow) arrow.classList.remove('rotate-180');

        const sortOptions = {
            'create_time': '默认正序',
            'reply_time': '回复倒序',
            'likes': '点赞倒序'
        };

        if (label) {
            label.textContent = sortOptions[sortValue] || '默认正序';
        }

        // 更新选中状态
        document.querySelectorAll('[data-check]').forEach(check => {
            if (check.dataset.check === sortValue) {
                check.classList.remove('hidden');
            } else {
                check.classList.add('hidden');
            }
        });

        // 重置页面并重新加载评论
        this.currentPage = 1;
        this.clearComments();
        this.loadComments();
    }

    // 清空评论列表
    clearComments() {
        const container = document.getElementById('comments-list');
        if (container) {
            container.innerHTML = '';
        }
    }

    handleClickOutside(event) {
        const target = event.target;
        const dropdown = target.closest('.sort-dropdown');
        const menu = document.getElementById('sort-dropdown-menu');
        const menuContainer = target.closest('#sort-dropdown-menu');

        // 如果点击的不是下拉菜单相关元素，且菜单是打开的，则关闭菜单
        if (!dropdown && !menuContainer && menu && !menu.classList.contains('hidden')) {
            this.toggleSortDropdown();
        }
    }

    // 图片上传处理
    async handleImageUpload(event) {
        const files = event.target.files;
        if (!files || files.length === 0) return;

        // 验证文件
        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            if (!file.type.startsWith('image/')) {
                showError(`${file.name} 不是有效的图片文件`);
                event.target.value = '';
                return;
            }
            if (file.size > 10 * 1024 * 1024) {
                showError(`${file.name} 文件大小超过10MB`);
                event.target.value = '';
                return;
            }
        }

        this.isUploading = true;
        this.uploadProgress = 0;
        this.showUploadProgress();

        try {
            const uploadPromises = Array.from(files).map((file, index) =>
                this.uploadSingleImage(file, index, files.length)
            );
            const results = await Promise.all(uploadPromises);

            let successCount = 0;
            let failCount = 0;

            results.forEach((result, index) => {
                if (result.code === 1) {
                    this.uploadedImages.push(result.data);
                    successCount++;
                } else {
                    showError(result.msg || `第${index + 1}张图片上传失败`);
                    failCount++;
                }
            });

            // 只有在有成功上传的文件时才显示成功提示
            if (successCount > 0) {
                if (failCount > 0) {
                    showSuccess(`${successCount}张图片上传成功，${failCount}张失败`);
                } else {
                    showSuccess('图片上传成功');
                }
                this.renderUploadedImages();
            }
        } catch (error) {
            showError('图片上传失败');
        } finally {
            this.isUploading = false;
            this.uploadProgress = 0;
            this.hideUploadProgress();
            event.target.value = '';
        }
    }

    // 单个图片上传
    uploadSingleImage(file, index, total) {
        return new Promise((resolve, reject) => {
            const formData = new FormData();
            formData.append('file', file);

            $.ajax({
                url: '/web/comment/uploadImage',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: 'json',
                xhr: () => {
                    const xhr = new window.XMLHttpRequest();
                    xhr.upload.addEventListener('progress', (e) => {
                        if (e.lengthComputable) {
                            const fileProgress = (e.loaded / e.total) * 100;
                            const totalProgress = ((index + fileProgress / 100) / total) * 100;
                            this.uploadProgress = Math.round(totalProgress);
                            this.updateUploadProgress();
                        }
                    });
                    return xhr;
                },
                success: resolve,
                error: reject
            });
        });
    }

    // 文件上传处理
    async handleFileUpload(event) {
        const files = event.target.files;
        if (!files || files.length === 0) return;

        // 验证文件大小
        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            if (file.size > 50 * 1024 * 1024) {
                showError(`${file.name} 文件大小超过50MB`);
                event.target.value = '';
                return;
            }
        }

        this.isUploading = true;
        this.uploadProgress = 0;
        this.showUploadProgress();

        try {
            const uploadPromises = Array.from(files).map((file, index) =>
                this.uploadSingleFile(file, index, files.length)
            );
            const results = await Promise.all(uploadPromises);

            let successCount = 0;
            let failCount = 0;

            results.forEach((result, index) => {
                if (result.code === 1) {
                    this.uploadedFiles.push(result.data);
                    successCount++;
                } else {
                    showError(result.msg || `第${index + 1}个文件上传失败`);
                    failCount++;
                }
            });

            // 只有在有成功上传的文件时才显示成功提示
            if (successCount > 0) {
                if (failCount > 0) {
                    showSuccess(`${successCount}个附件上传成功，${failCount}个失败`);
                } else {
                    showSuccess('附件上传成功');
                }
                this.renderUploadedFiles();
            }
        } catch (error) {
            showError('附件上传失败');
        } finally {
            this.isUploading = false;
            this.uploadProgress = 0;
            this.hideUploadProgress();
            event.target.value = '';
        }
    }

    // 单个文件上传
    uploadSingleFile(file, index, total) {
        return new Promise((resolve, reject) => {
            const formData = new FormData();
            formData.append('file', file);

            $.ajax({
                url: '/web/comment/uploadAttachment',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: 'json',
                xhr: () => {
                    const xhr = new window.XMLHttpRequest();
                    xhr.upload.addEventListener('progress', (e) => {
                        if (e.lengthComputable) {
                            const fileProgress = (e.loaded / e.total) * 100;
                            const totalProgress = ((index + fileProgress / 100) / total) * 100;
                            this.uploadProgress = Math.round(totalProgress);
                            this.updateUploadProgress();
                        }
                    });
                    return xhr;
                },
                success: resolve,
                error: reject
            });
        });
    }

    // 更新上传进度
    updateUploadProgress() {
        const bar = document.getElementById('upload-progress-bar');
        const text = document.getElementById('upload-progress-text');

        if (bar) {
            bar.style.width = this.uploadProgress + '%';
        }
        if (text) {
            text.textContent = this.uploadProgress + '%';
        }
    }

    // 渲染已上传的图片
    renderUploadedImages() {
        const container = document.getElementById('uploaded-images-container');
        const list = document.getElementById('uploaded-images-list');

        if (this.uploadedImages.length > 0) {
            container.classList.remove('hidden');
            list.innerHTML = this.uploadedImages.map((image, index) => `
                <div class="relative">
                    <img src="${image.url}" alt="${image.name}" class="w-20 h-20 object-cover rounded">
                    <button class="absolute -top-2 -right-2 w-6 h-6 bg-red-500 text-white rounded-full text-xs hover:bg-red-600 transition-colors" onclick="window.commentsManager.removeImage(${index})">×</button>
                </div>
            `).join('');
        } else {
            container.classList.add('hidden');
        }
    }

    // 渲染已上传的文件
    renderUploadedFiles() {
        const container = document.getElementById('uploaded-files-container');
        const list = document.getElementById('uploaded-files-list');

        if (this.uploadedFiles.length > 0) {
            container.classList.remove('hidden');
            list.innerHTML = this.uploadedFiles.map((file, index) => `
                <div class="flex items-center gap-3 p-2 bg-gray-100 rounded-lg">
                    <i class="fas fa-file w-5 h-5 text-gray-500"></i>
                    <div class="flex-1 min-w-0">
                        <div class="text-sm font-medium text-blue-600 truncate">${file.name}</div>
                        <div class="text-xs text-gray-500">${this.formatFileSize(file.size)}</div>
                    </div>
                    <button class="w-6 h-6 bg-red-500 text-white rounded-full text-xs hover:bg-red-600 transition-colors" onclick="window.commentsManager.removeFile(${index})">×</button>
                </div>
            `).join('');
        } else {
            container.classList.add('hidden');
        }
    }

    // 移除图片
    removeImage(index) {
        this.uploadedImages.splice(index, 1);
        this.renderUploadedImages();
    }

    // 移除文件
    removeFile(index) {
        this.uploadedFiles.splice(index, 1);
        this.renderUploadedFiles();
    }

    // 格式化文件大小
    formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
    }
}

// 全局函数，供模板调用
function handleCommentLike(commentId) {
    if (!window.commentsManager || !window.commentsManager.userInfo) {
        showError('请先登录');
        return;
    }

    $.ajax({
        url: '/web/comment/like',
        type: 'POST',
        data: { comment_id: commentId },
        dataType: 'json',
        success: function (response) {
            if (response.code === 1) {
                showSuccess(response.msg || '操作成功');

                // 更新点赞状态和数量，避免刷新页面
                const $likeBtn = $(`[data-comment-id="${commentId}"] .fa-thumbs-up`).closest('button');
                const $likeCount = $likeBtn.find('span');

                if (response.data.is_liked) {
                    $likeBtn.find('i').addClass('text-blue-600');
                    $likeCount.addClass('text-blue-600');
                } else {
                    $likeBtn.find('i').removeClass('text-blue-600');
                    $likeCount.removeClass('text-blue-600');
                }

                $likeCount.text(response.data.likes > 0 ? response.data.likes : '赞');
            } else {
                showError(response.msg || '操作失败');
            }
        },
        error: function () {
            showError('网络连接失败');
        }
    });
}

function handleCommentReply(commentId) {
    // 预留且不再需要    
}

// 删除评论
function handleCommentDelete(commentId) {
    if (!window.commentsManager || !window.commentsManager.userInfo) {
        showError('请先登录');
        return;
    }

    // 确认删除
    if (!confirm('确定要删除这条评论吗？')) {
        return;
    }

    $.ajax({
        url: '/web/comment/delete',
        type: 'POST',
        data: { comment_id: commentId },
        dataType: 'json',
        success: function (response) {
            if (response.code === 1) {
                showSuccess(response.msg || '删除成功');

                // 移除评论元素
                const $comment = $(`[data-comment-id="${commentId}"]`);
                const $reply = $(`[data-reply-id="${commentId}"]`);

                if ($comment.length) {
                    $comment.fadeOut(300, function () {
                        $(this).remove();

                        // 如果没有评论了，显示空状态
                        if ($('[data-comment-id]').length === 0) {
                            window.commentsManager.showEmptyState();
                        }
                    });
                }

                if ($reply.length) {
                    $reply.fadeOut(300, function () {
                        $(this).remove();
                    });
                }

                // 更新评论总数
                const $total = $('#comments-total');
                const currentTotal = parseInt($total.text());
                if (!isNaN(currentTotal) && currentTotal > 0) {
                    $total.text(currentTotal - 1);
                }
            } else {
                showError(response.msg || '删除失败');
            }
        },
        error: function () {
            showError('网络连接失败');
        }
    });
}

// 加载更多回复
function loadMoreReplies(commentId) {
    if (!commentId) return;

    const $loadMoreBtn = $(`[data-comment-id="${commentId}"] button:contains("查看更多回复")`);
    $loadMoreBtn.html('<i class="fas fa-spinner fa-spin mr-1"></i> 加载中...');

    $.ajax({
        url: '/web/comment/replies',
        type: 'GET',
        data: {
            comment_id: commentId,
            page: 2  // 默认第一页已经加载，这里加载第二页
        },
        dataType: 'json',
        success: function (response) {
            if (response.code === 1 && response.data.list) {
                const replies = response.data.list;

                if (replies.length > 0) {
                    // 渲染回复并添加到列表
                    replies.forEach(reply => {
                        const replyHtml = window.commentsManager.renderReplyItem(reply);
                        $loadMoreBtn.before(replyHtml);
                    });

                    // 如果没有更多回复，移除加载更多按钮
                    if (!response.data.has_more) {
                        $loadMoreBtn.remove();
                    } else {
                        $loadMoreBtn.html(`查看更多回复 (${response.data.total - response.data.page * response.data.limit})`);
                    }
                } else {
                    $loadMoreBtn.remove();
                }
            } else {
                $loadMoreBtn.html('加载失败，点击重试');
                showError(response.msg || '加载回复失败');
            }
        },
        error: function () {
            $loadMoreBtn.html('加载失败，点击重试');
            showError('网络连接失败');
        }
    });
}

// 图片预览
function openImagePreview(images, index) {
    if (!images || !images[index]) return;

    // 使用画廊预览
    openImageGallery(images, index);
}

// 从data属性获取图片数据并预览
function openImagePreviewFromData(element) {
    try {
        const images = JSON.parse(element.getAttribute('data-images'));
        const index = parseInt(element.getAttribute('data-index'), 10);

        if (images && images[index]) {
            openImageGallery(images, index);
        }
    } catch (error) {
        console.error('图片预览失败:', error);
    }
}

// 图片画廊预览功能
function openImageGallery(images, startIndex = 0) {
    if (!images || images.length === 0) return;

    // 如果有GLightbox，使用GLightbox
    if (typeof GLightbox !== 'undefined') {
        // 动态创建lightbox链接
        const lightboxHtml = images.map((image, index) =>
            `<a href="${image}" class="glightbox-comment" data-gallery="comment-gallery" data-title="评论图片 ${index + 1}"></a>`
        ).join('');

        // 临时添加到页面
        const $tempContainer = $('<div style="display:none;">').html(lightboxHtml);
        $('body').append($tempContainer);

        // 初始化GLightbox
        const lightbox = GLightbox({
            selector: '.glightbox-comment',
            startAt: startIndex,
            touchNavigation: true,
            keyboardNavigation: true,
            closeOnOutsideClick: true,
            loop: true,
            zoomable: true,
            draggable: true,
            skin: 'clean'
        });

        // 打开lightbox
        lightbox.open();

        // 清理临时元素
        setTimeout(() => $tempContainer.remove(), 100);
    } else {
        // 降级方案：使用自定义画廊
        openCustomImageGallery(images, startIndex);
    }
}

// 自定义图片画廊（降级方案）
function openCustomImageGallery(images, startIndex = 0) {
    let currentIndex = startIndex;

    // 创建画廊HTML
    const galleryHtml = `
        <div id="custom-image-gallery" class="fixed inset-0 bg-black bg-opacity-90 flex items-center justify-center z-50" onclick="closeCustomGallery(event)">
            <div class="relative max-w-4xl max-h-full p-4" onclick="event.stopPropagation()">
                <!-- 关闭按钮 -->
                <button onclick="closeCustomGallery()" class="absolute top-2 right-2 text-white text-3xl hover:text-gray-300 z-10">
                    <i class="fas fa-times"></i>
                </button>

                <!-- 图片容器 -->
                <div class="relative">
                    <img id="gallery-image" src="${images[currentIndex]}" alt="评论图片"
                         class="max-w-full max-h-[80vh] object-contain mx-auto">

                    <!-- 导航按钮 -->
                    ${images.length > 1 ? `
                        <button onclick="prevImage()" class="absolute left-4 top-1/2 transform -translate-y-1/2 text-white text-2xl hover:text-gray-300 bg-black bg-opacity-50 rounded-full w-12 h-12 flex items-center justify-center">
                            <i class="fas fa-chevron-left"></i>
                        </button>
                        <button onclick="nextImage()" class="absolute right-4 top-1/2 transform -translate-y-1/2 text-white text-2xl hover:text-gray-300 bg-black bg-opacity-50 rounded-full w-12 h-12 flex items-center justify-center">
                            <i class="fas fa-chevron-right"></i>
                        </button>
                    ` : ''}
                </div>

                <!-- 图片信息 -->
                <div class="text-center mt-4">
                    <span class="text-white text-sm">
                        ${images.length > 1 ? `${currentIndex + 1} / ${images.length}` : '1 / 1'}
                    </span>
                </div>

                <!-- 缩略图导航 -->
                ${images.length > 1 ? `
                    <div class="flex justify-center mt-4 space-x-2 max-w-full overflow-x-auto">
                        ${images.map((img, index) => `
                            <img src="${img}" alt="缩略图"
                                 class="w-16 h-16 object-cover rounded cursor-pointer border-2 ${index === currentIndex ? 'border-white' : 'border-transparent'} hover:border-gray-300"
                                 onclick="setCurrentImage(${index})">
                        `).join('')}
                    </div>
                ` : ''}
            </div>
        </div>
    `;

    // 添加到页面
    $('body').append(galleryHtml);

    // 存储图片数组和当前索引到全局变量
    window.galleryImages = images;
    window.galleryCurrentIndex = currentIndex;

    // 绑定键盘事件
    $(document).on('keydown.gallery', function (e) {
        switch (e.keyCode) {
            case 27: // ESC
                closeCustomGallery();
                break;
            case 37: // 左箭头
                if (images.length > 1) prevImage();
                break;
            case 39: // 右箭头
                if (images.length > 1) nextImage();
                break;
        }
    });
}

// 关闭自定义画廊
function closeCustomGallery(event) {
    if (event && event.target !== event.currentTarget) return;

    $('#custom-image-gallery').remove();
    $(document).off('keydown.gallery');
    delete window.galleryImages;
    delete window.galleryCurrentIndex;
}

// 上一张图片
function prevImage() {
    if (!window.galleryImages || window.galleryImages.length <= 1) return;

    window.galleryCurrentIndex = window.galleryCurrentIndex > 0 ?
        window.galleryCurrentIndex - 1 :
        window.galleryImages.length - 1;

    updateGalleryImage();
}

// 下一张图片
function nextImage() {
    if (!window.galleryImages || window.galleryImages.length <= 1) return;

    window.galleryCurrentIndex = window.galleryCurrentIndex < window.galleryImages.length - 1 ?
        window.galleryCurrentIndex + 1 :
        0;

    updateGalleryImage();
}

// 设置当前图片
function setCurrentImage(index) {
    if (!window.galleryImages || index < 0 || index >= window.galleryImages.length) return;

    window.galleryCurrentIndex = index;
    updateGalleryImage();
}

// 更新画廊图片
function updateGalleryImage() {
    const $img = $('#gallery-image');
    const $counter = $('#custom-image-gallery .text-center span');

    if ($img.length && window.galleryImages) {
        $img.attr('src', window.galleryImages[window.galleryCurrentIndex]);
        $counter.text(`${window.galleryCurrentIndex + 1} / ${window.galleryImages.length}`);

        // 更新缩略图边框
        $('#custom-image-gallery .w-16').removeClass('border-white').addClass('border-transparent');
        $('#custom-image-gallery .w-16').eq(window.galleryCurrentIndex).removeClass('border-transparent').addClass('border-white');
    }
}

// 下载文件
function downloadFile(url, name) {
    if (!url) return;

    const link = $('<a></a>')
        .attr('href', url)
        .attr('download', name || '')
        .attr('target', '_self')
        .appendTo('body');

    link[0].click();
    link.remove();
}

// 显示成功提示
function showSuccess(message) {
    if (window.toast && window.toast.success) {
        window.toast.success(message);
    } else if (window.showSuccess) {
        window.showSuccess(message);
    } else if ($.toast) {
        $.toast({
            heading: '成功',
            text: message,
            showHideTransition: 'slide',
            icon: 'success',
            position: 'top-right',
            hideAfter: 3000
        });
    } else {
        // 使用统一的toast系统，避免使用alert
        console.log('Success:', message);
        // 创建简单的toast提示
        createSimpleToast(message, 'success');
    }
}

// 显示错误提示
function showError(message) {
    if (window.toast && window.toast.error) {
        window.toast.error(message);
    } else if (window.showError) {
        window.showError(message);
    } else if ($.toast) {
        $.toast({
            heading: '错误',
            text: message,
            showHideTransition: 'slide',
            icon: 'error',
            position: 'top-right',
            hideAfter: 5000
        });
    } else {
        // 使用统一的toast系统，避免使用alert
        console.error('Error:', message);
        // 创建简单的toast提示
        createSimpleToast(message, 'error');
    }
}

// 创建简单的toast提示（备用方案）
function createSimpleToast(message, type) {
    const toast = document.createElement('div');
    toast.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: ${type === 'success' ? '#10b981' : '#ef4444'};
        color: white;
        padding: 12px 20px;
        border-radius: 8px;
        font-size: 14px;
        z-index: 10000;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        transform: translateX(100%);
        transition: transform 0.3s ease;
    `;
    toast.textContent = message;

    document.body.appendChild(toast);

    // 显示动画
    setTimeout(() => {
        toast.style.transform = 'translateX(0)';
    }, 100);

    // 自动移除
    setTimeout(() => {
        toast.style.transform = 'translateX(100%)';
        setTimeout(() => {
            if (toast.parentNode) {
                toast.parentNode.removeChild(toast);
            }
        }, 300);
    }, type === 'success' ? 3000 : 5000);
}
